
import React, { PureComponent } from 'react'

import { Select, Form, Input, Row, Col, Button, TimePicker, Checkbox, Switch } from 'antd';
import { connect } from 'react-redux'
const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
import PageBackHeader from "@common/PageBackHeader";
import { withRouter } from 'react-router-dom'
import MapSelector from '@common/presentational/MapSelector'
import { EXPRESS_TYPES } from '@constants/ExpressTypes'
import { getBilinInfo } from "@utils/localStorage";
import moment from 'moment';
import { getStoreSelection } from "@sagas/storeManagement";
import { editWarehouse, creatWarehouse } from "@sagas/warehouse/warehouseManagement";
import { getHistoryMatchParams } from "@utils/setUrlQuery";

const getReformedData = (data) => {
    const _data = {
        ...data
    }
    let expressType = []
    _data.pickUp && expressType.push('pickUp')
    _data.ordinaryExpress && expressType.push('ordinaryExpress')
    _data.cityExpress && expressType.push('cityExpress')
    return {
        ..._data,
        type: _data.storeId ? 1 : 0,
        addressInfo: {
            address: _data.address,
            latitude: _data.latitude,
            longitude: _data.longitude,
            cityCode: _data.cityCode || null,
            regionCode: _data.regionCode,
        },
        deadline: moment(_data.deadline || '00:00', "HH:mm"),
        expressType,
        storageMode: !!_data.storageMode
    }
}

const initialValue = {
    name: '',
    type: 0,
    addressInfo: {
        address: '',               // 地址，必填非空（100字）
        latitude: '',
        longitude: '',          // 经纬度
        regionCode: null,       // 城市编码
        cityCode: null,
    },
    contact: '',
    mobile: '',
    expressType: [],
    deadline: moment('00:00', "HH:mm"),
    storageMode: false
}
function mapStateToProps(state) {
    const { storeManagement } = state
    return {
        storeSelection: storeManagement.storeSelection,
    }
}

@connect(
    mapStateToProps
    , {
        getStoreSelection,
        creatWarehouse,
        editWarehouse
    })
@withRouter
class WarehouseCreate extends PureComponent {

    constructor(props) {
        super(props);
        const { location } = props
        const { id } = getHistoryMatchParams(props)
        const { state } = location
        this.state = {
            id,
            formData: id ? {
                ...initialValue,
                ...getReformedData(state),
            } : {
                ...initialValue
            }
        }

        this.formRef = React.createRef()

        this.handleSubmit = this.handleSubmit.bind(this)
        this.submitForm = this.submitForm.bind(this)
        this.cancelFunc = this.cancelFunc.bind(this)
        this.handleAddressInfo = this.handleAddressInfo.bind(this)
        this.getStoreSelection = this.getStoreSelection.bind(this)
    }

    componentDidMount() {
        this.getStoreSelection()
    }

    getStoreSelection() {
        this.props.getStoreSelection({
            route: 'ADMIN',
        })
    }


    handleSubmit(values) {
        const { id, formData } = this.state
        const _value = {
            ...values.addressInfo,
            storeId: values.storeId ? Number(values.storeId) : 0,
            name: values.name,
            contact: values.contact,
            mobile: values.mobile,
            deadline: values.deadline.format("HH:mm:ss"),
            storageMode: values.storageMode ? 1 : 0,
            pickUp: values.expressType.includes('pickUp'),
            cityExpress: values.expressType.includes('cityExpress'),
            ordinaryExpress: values.expressType.includes('ordinaryExpress'),
        }
        if (values.type === 0) {
            _value.cityCode = values.addressInfo.cityCode
        }
        if (id) {
            this.props.editWarehouse({
                ..._value,
                id: formData.id,
            }, () => {
                this.cancelFunc()
            })
        } else {
            this.props.creatWarehouse({
                ..._value,
            }, () => {
                this.cancelFunc()
            })
        }
    }

    submitForm() {
        this.formRef.current?.submit()
    }

    cancelFunc() {
        this.props.goBack ? this.props.goBack('/warehouse/manage') : this.props.history.goBack('/warehouse/manage')
    }

    handleAddressInfo(rule, value, callback) {
        const { latitude, longitude, address } = value
        if (!address) {
            callback('请输入地址')
        } else if (address.length > 50) {
            callback('地址长度不能超过50')
        } else if (!latitude || !longitude) {
            callback('请在地图上选择定位店铺位置')
        } else {
            callback()
        }
    }

    render() {
        const { formData, id } = this.state
        const { storeSelection } = this.props
        const isEdit = !!id
        return (
            <div className="bilin-web">
                <PageBackHeader title={isEdit ? '编辑仓库' : '新建仓库'} />
                <div className="bilin-web-body form-page with-footer">
                    <Form
                        ref={this.formRef}
                        name="warehouse-edit"
                        className='pdt-36'
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        initialValues={formData}
                        scrollToFirstError={{
                            behavior: actions =>
                                actions.forEach(({ el, top, left }) => {
                                    el.scrollTop = top - 100
                                    el.scrollLeft = left
                                }),
                        }}
                        onFinish={this.handleSubmit}
                    >
                        {getBilinInfo('storeId') ? null : <FormItem
                            label="仓库类型: "
                            name="type"
                            rules={[
                                { required: true, message: '请选择仓库类型', },
                            ]}
                        >
                            <Select
                                disabled={isEdit}
                                placeholder="请选择仓库类型"
                                style={{ display: 'inline-block', width: 300 }}
                            >
                                <Select.Option key={0} value={0}>总部仓</Select.Option>
                                <Select.Option key={1} value={1}>店铺仓</Select.Option>
                            </Select>
                        </FormItem>}
                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}
                        >
                            {({ getFieldValue }) => {
                                return getFieldValue('type') === 1 ? (
                                    <Form.Item
                                        name="storeId"
                                        label="店铺"
                                        rules={[
                                            { required: true, message: '店铺名', },
                                        ]}
                                    >
                                        <Select
                                            disabled={isEdit}
                                            placeholder="请选择店铺"
                                            style={{ display: 'inline-block', width: 300 }}
                                        >
                                            {(storeSelection || []).map(store => (
                                                <Select.Option
                                                    key={store.store_id}
                                                    value={store.store_id}
                                                >
                                                    {store.store_name}
                                                </Select.Option>
                                            ))}
                                        </Select>
                                    </Form.Item>
                                ) : null
                            }}
                        </Form.Item>
                        <FormItem
                            label="仓库名称: "
                            name='name'
                            rules={[
                                { required: true, message: '请输入名称', },
                            ]}
                        >
                            <Input style={{ width: 300 }} placeholder="请输入名称" />
                        </FormItem>
                        <FormItem
                            label="联系人: "
                            name='contact'
                            rules={[
                                { required: true, message: '请输入联系人', },
                            ]}
                        >
                            <Input maxLength={10} style={{ width: 300 }} placeholder="请输入联系人" />
                        </FormItem>
                        <FormItem
                            label="联系方式: "
                            name='mobile'
                            rules={[
                                { required: true, message: '请输入手机号', },
                            ]}
                        >
                            <Input maxLength={11} style={{ width: 300 }} placeholder="请输入手机号" />
                        </FormItem>
                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}
                        >
                            {({ getFieldValue }) => {
                                return isEdit || getFieldValue('type') === 0?  (
                                    <FormItem
                                        label="仓库地址: "
                                        name='addressInfo'
                                        rules={[
                                            { required: true, message: '请输入仓库地址', },
                                            { validator: this.handleAddressInfo, },
                                        ]}
                                    >
                                        <MapSelector />
                                    </FormItem>
                                ) : null
                            }}
                        </Form.Item>

                        <FormItem
                            label="配送方式: "
                            name='expressType'
                            rules={[
                                { required: false, message: '请选择配送方式', },
                            ]}
                        >
                            <CheckboxGroup
                                options={EXPRESS_TYPES}
                            />
                        </FormItem>
                        <FormItem
                            valuePropName='checked'
                            label="启用库存管理: "
                            name='storageMode'
                            rules={[
                                { required: true, message: '请选择是否启用库存管理', },
                            ]}
                            extra="开启后,将精确管理库存,当库存为0时,不能售卖"
                        >
                            <Switch />
                        </FormItem>
                        <FormItem
                            label="截止下单日期: "
                            name='deadline'
                            rules={[
                                { required: true, message: '请选择截止时间', },
                            ]}
                        >
                            <TimePicker format="HH:mm" placeholder="截止时间" style={{ width: 120 }} />
                        </FormItem>
                    </Form>
                </div>
                <div className="bilin-web-footer">
                    <Button type="primary" ghost onClick={this.cancelFunc}>取消</Button>
                    <Button type="primary" onClick={this.submitForm}>{isEdit ? '确定修改' : '确定创建'}</Button>
                </div>
            </div>

        )
    }
}

export default WarehouseCreate